package com.hqq.behaviour.command;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Deque;
import java.util.LinkedList;

/**
 * Wizard
 * 请求者角色Invoker--负责调用命令对象执行请求，相关的方法叫做行动方法。
 * Created by heqianqian on 2017/6/15.
 */
public class Wizard {

    private static final Logger logger = LoggerFactory.getLogger(Wizard.class);

    private Deque<Command> undoStack = new LinkedList<>();
    private Deque<Command> redoStack = new LinkedList<>();

    public Wizard() {
    }

    public void castSpell(Command command, Target target) {
        logger.info("{} casts {} at {}", this, command, target);
        command.execute(target);
        undoStack.offerLast(command);
    }

    public void undoLastSpell() {
        if (!undoStack.isEmpty()) {
            Command previousCommand = undoStack.pollLast();
            logger.info("{} undoes {}", this, previousCommand);
            previousCommand.undo();
            redoStack.offerLast(previousCommand);
        }
    }

    public void redoLastSpell() {
        if (!redoStack.isEmpty()) {
            Command previousCommand = redoStack.pollLast();
            logger.info("{} redoes {}", this, previousCommand);
            previousCommand.redo();
            undoStack.offerLast(previousCommand);
        }
    }

    @Override
    public String toString() {
        return "Wizard";
    }
}
